package com.dadi.myintentservice;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.Nullable;

/**
 * author: 韦敏敏
 * date: 2019/12/12 0012
 */
public class UploadImgService extends IntentService {
    private static final String ACTION_UPLOAD_IMG = "com.dadi.myintentservice.action.UpLOAD_IMAGE";
    public static final String EXTRA_IMG_PATH = "com.dadi.myintentservice.extra.IMG_PATH";
    public static void startUploadImg(Context context, String path){
        Intent intent = new Intent(context, UploadImgService.class);
        intent.setAction(ACTION_UPLOAD_IMG);
        intent.putExtra(EXTRA_IMG_PATH, path);
        context.startService(intent);
    }
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public UploadImgService() {
        super("UploadImgService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if(intent != null){
            String action = intent.getAction();
            if(ACTION_UPLOAD_IMG.equals(action)){
                String path = intent.getStringExtra(EXTRA_IMG_PATH);
                handleUploadImg(path);
            }
        }
    }
    private void handleUploadImg(String path) {
        try {
            // 模拟上传耗时
            Thread.sleep(2000);
            Intent intent = new Intent(MainActivity.UPLOAD_RESULT);
            intent.putExtra(EXTRA_IMG_PATH, path);
            sendBroadcast(intent);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("TAG", "onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TAG", "onDestroy");
    }
}
